<?php

namespace App\Trip\Passengers;

use App\Facades\SnowFlakeFacade;
use App\Models\Common\Passengers\CommonPassenger;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class CommonPassengerManager
{


    private string $cache_key;
    private string $cache_key_id2pid;
    private string $cache_key_pid2id;

    public function __construct()
    {
        $this->cache_key        = "common_passengers_manager";
        $this->cache_key_id2pid = "common_passengers_manager:id2pid";
        $this->cache_key_pid2id = "common_passengers_manager:pid2id";
    }

    public function getIdentityCodeByPassengerId(string $passenger_id)
    {
        return Redis::hget($this->cache_key_pid2id, $passenger_id);
    }

    /**
     * @throws Exception
     */
    public function generatePassengerIdByIdentityCode(string $identity_code)
    {
        // 查询缓存
        if ($passenger_id = $this->getPassengerIdByIdentityCode($identity_code)) {
            return $passenger_id;
        }
        $common_passenger = new CommonPassenger();
        if ($cp = $common_passenger->getByIdentityCode($identity_code)) {
            return $cp->getPassengerId();
        }
        try {
            $passenger_id = SnowFlakeFacade::id();
            $this->setPassengerIdByIdentityCode($identity_code, $passenger_id);
            $common_passenger->create(compact('passenger_id', 'identity_code'));
            $this->setIdentityCodeByPassengerId($passenger_id, $identity_code);
            return $passenger_id;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    // 生成passengerId

    public function getPassengerIdByIdentityCode(string $identity_code)
    {
        return Redis::hget($this->cache_key_id2pid, $identity_code);
    }

    private function setPassengerIdByIdentityCode(string $identity_code, string $passenger_id): void
    {
        if (Redis::hexists($this->cache_key_id2pid, $identity_code)) {
            return;
        }
        Redis::hset($this->cache_key_id2pid, $identity_code, $passenger_id);
    }

    private function setIdentityCodeByPassengerId(string $passenger_id, string $identity_code): void
    {
        if (Redis::hexists($this->cache_key_pid2id, $passenger_id)) {
            return;
        }
        Redis::hset($this->cache_key_pid2id, $passenger_id, $identity_code);
    }

    /**
     * 乘客id压入缓存
     *
     * @param string $passenger_id
     *
     * @return bool
     */
    public function addPassengerId(string $passenger_id): bool
    {
        return Cache::sadd($this->cache_key, $passenger_id) == 1;
    }

    /**
     * 乘客id 移除缓存
     *
     * @param string $passenger_id
     *
     * @return bool
     */
    public function remPassengerId(string $passenger_id): bool
    {
        return Cache::srem($this->cache_key, $passenger_id) == 1;
    }
}